package com.insta.formation.calendar.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum HibernateUtil
{
	INSTANCE;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);

	private Session session;
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Log exception!
			throw new ExceptionInInitializerError(ex);
		}
	}

	public Session getSession() throws HibernateException
	{
		if (session == null) {
			session = sessionFactory.openSession(); 
		}
		return session;
	}
	
	public void closeSession() {

		if (session != null) {

			try {
				getSession().close();
			} catch (HibernateException e) {
				LOGGER.error(e.getMessage());
			} finally {
				session = null;
			}
		}
	}
}